package com.leetcode.weekly.contest.no288th;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 覃国强
 * @date 2022-04-10 10:38
 */
public class A01_按奇偶性交换后的最大数字 {


  static
  class Solution {
    public int largestInteger(int num) {
      if (num < 10) {
        return num;
      }
      List<NumUnit> numUnits = new ArrayList<>();
      int base = 1;
      while (num > 0) {
        int value = num % 10;
        num /= 10;
        numUnits.add(new NumUnit(value, base));
        base *= 10;
      }

      for (int targetIndex = numUnits.size() - 1; targetIndex > 0; --targetIndex) {
        NumUnit target = numUnits.get(targetIndex);
        NumUnit candidate = numUnits.get(targetIndex);
        for (int i = 0; i < targetIndex; ++i) {
          NumUnit tempCandidate = numUnits.get(i);
          if ((candidate.value + tempCandidate.value) % 2 == 0 && tempCandidate.value > candidate.value) {
            candidate = tempCandidate;
          }
        }
        if (target != candidate) {
          int value = target.value;
          target.value = candidate.value;
          candidate.value = value;
        }
      }
      int answer = 0;
      for (NumUnit numUnit : numUnits) {
        answer += numUnit.value * numUnit.base;
      }
      return answer;
    }

    static class NumUnit {
      int value;
      int base;

      NumUnit(int value, int base) {
        this.value = value;
        this.base = base;
      }
    }
  }

}
